package com.lmxdawn.api.dnf.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.ExtUserInfo;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.lmxdawn.api.admin.util.RedisUtil;
import com.lmxdawn.api.common.res.BaseResponse;
import com.lmxdawn.api.common.util.ResultVOUtils;
import com.lmxdawn.api.dnf.entity.Order;
import com.lmxdawn.api.dnf.entity.RealName;
import com.lmxdawn.api.dnf.service.IRealnameService;
import com.lmxdawn.api.dnf.config.MQConfig;
import com.lmxdawn.api.dnf.service.OrderService;
import com.lmxdawn.api.dnf.annotation.LoginIgnore;
import com.lmxdawn.api.dnf.dto.CommonReq;
import com.lmxdawn.api.im.service.ImUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import lombok.var;
import org.jim.core.ImPacket;
import org.jim.core.packets.ChatBody;
import org.jim.server.JimServerAPI;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.util.*;

import static org.jim.core.packets.Command.COMMAND_UNKNOW;

/**
 * @author: HuGoldWater
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/web/dnf/mall/payment")
public class AlipayController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    OrderService orderService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IRealnameService realnameService;

    @LoginIgnore
    @GetMapping(value="/qrCode")
    public void qrCode(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws IOException {
        String orderId = request.getParameter("orderId");
        Object o = redisUtil.get(orderId);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print(o == null? "订单不存在："+orderId:o.toString());
    }
    /**
     * 前往支付宝进行支付
     *
     * @return
     */
    @LoginIgnore
    @PostMapping(value="/goAlipay")
    public BaseResponse goAlipay(
            @RequestBody CommonReq<Map> req
    ) throws Exception{

        var content = req.getContent();
        var merchantOrderId = MapUtil.getStr(content, "orderId");
        val alipayConfig = orderService.getConfig(merchantOrderId);
        val order = orderService.findById(merchantOrderId);
        RealName realName = realnameService.lambdaQuery().eq(RealName::getUserId, order.getUserId()).one();
        // 商户订单号, 商户网站订单系统中唯一订单号, 必填
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        request.setReturnUrl("http://www.5808d.com/file/pay_success.html");
        request.setNotifyUrl("http://www.5808d.com/api/web/dnf/mall/payment/alipay");

        // 设置订单标题
        model.setSubject(order.getRemark());
        // 设置请求来源地址
        model.setRequestFromUrl("http://www.5808d.com/");
        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        // 设置PC扫码支付的方式
        model.setQrPayMode("4");
        // 设置商户自定义二维码宽度
        model.setQrcodeWidth(300L);
        // 设置请求后页面的集成方式
        model.setIntegrationType("PCWEB");
        // 设置商户的原始订单号
        model.setMerchantOrderNo(merchantOrderId);
        // 设置商户订单号
        model.setOutTradeNo(merchantOrderId);

        // 设置订单总金额
        model.setTotalAmount(order.getTotalAmount().setScale(2, RoundingMode.HALF_UP)
                .toString());
//        model.setTotalAmount("0.01");

        ExtUserInfo extUserInfo = new ExtUserInfo();
        extUserInfo.setNeedCheckInfo("T");
        extUserInfo.setFixBuyer("T");
        extUserInfo.setMinAge("18");
        extUserInfo.setCertNo(realName.getIdNo());
        extUserInfo.setCertType("IDENTITY_CARD");
        extUserInfo.setName(realName.getRealname());
        model.setExtUserInfo(extUserInfo);
        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");
        AlipayTradePagePayResponse responseA = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = responseA.getBody();

        rabbitTemplate.convertAndSend("", MQConfig.ORDER_CREATE_QUEUE,merchantOrderId);
        log.info("send to {}, msg:{}", MQConfig.ORDER_CREATE_QUEUE, merchantOrderId);
        return ResultVOUtils.success(pageRedirectionData);
    }


    /**
     * 支付成功后的支付宝异步通知
     */
    @LoginIgnore
    @RequestMapping(value="/alipay")
    public String alipay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 商户订单号
        Map<String,String[]> requestParams = request.getParameterMap();
        String out_trade_no = request.getParameter("out_trade_no");
        if (StrUtil.isEmpty(out_trade_no)){
            log.info("支付提现后的支付宝异步通知:{}", JSON.toJSON(requestParams));
            return "success";
        }
        val alipayConfig = orderService.getConfig(out_trade_no);
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        log.info("支付成功后的支付宝异步通知:{}", JSON.toJSON(requestParams));
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//       valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCertCheckV1(params,
                alipayConfig.getAlipayPublicCertPath(),
                alipayConfig.getCharset(),
                alipayConfig.getSignType()); //调用SDK验证签名

        if(signVerified) {//验证成功
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            // 付款金额

            String refund_amount = request.getParameter("refund_fee");

            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            log.info("************* 支付宝异步通知 - 时间: {} *************", DateUtil.date());
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
            log.info("* 交易状态: {}", trade_status);
            log.info("*****************************************************************************");
            if (StrUtil.isEmpty(refund_amount)){
                if (trade_status.equals("TRADE_SUCCESS")){
                    orderService.updatePayStatus(out_trade_no, trade_no);
                    Map message = new HashMap();
                    message.put("orderId",out_trade_no);
                    message.put("transactionId",trade_no);
                    rabbitTemplate.convertAndSend("", MQConfig.ORDER_PAY, JSON.toJSONString(message));
                }
                ChatBody build = ChatBody.newBuilder()
                        .chatType(1)
                        .groupId(out_trade_no)
                        .from("admin")
                        .content("用户已支付")
                        .setCmd(99)
                        .msgType(0)
                        .build();
                ImPacket imPacket = new ImPacket(COMMAND_UNKNOW, JSON.toJSONString(build).getBytes());
                JimServerAPI.sendToGroup("0", imPacket);
            }else{
                log.info("退款成功，更新支付状态");
                orderService.lambdaUpdate().eq(Order::getId, out_trade_no)
                        .set(Order::getPaymentStatus, 3).update();
            }
            return "success";
        }else {
            //验证失败
            log.info("验签失败, 时间: {}", DateUtil.date());
            return "fail";
        }
    }

}